package com.itdaan.portal.business.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.itdaan.portal.business.domain.Page;
import com.itdaan.portal.business.domain.Role;
import com.itdaan.portal.business.domain.User;
import com.itdaan.portal.business.domain.UserRole;
import com.itdaan.portal.business.service.RoleService;
import com.itdaan.portal.business.service.UserRoleService;
import com.itdaan.portal.business.service.UserService;
import com.itdaan.portal.common.exception.ServiceException;

/**
 * 本站用户后台业务控制类
 * @author www.itdaan.com
 */
@Controller
@RequestMapping("/user/user")
public class UserController {

	private Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private ShiroDbRealm shiroDbRealm;

	@RequestMapping(value = "edit")
	public String edit(@ModelAttribute("preloadUser") User user, Model model) {
		List<Role> roles = new ArrayList<Role>();
		try {
			roles = roleService.getAll();
		} catch (ServiceException e) {
			logger.error("查询角色失败：{}",e.toString());
		}
		// 用于给之前选中的角色设置选中状态
		List<UserRole> userRoles = new ArrayList<UserRole>();
		try {
			userRoles = userRoleService.getByUserId(user.getId());
		} catch (ServiceException e) {
			logger.error("查询角色失败：{}",e.toString());
		}
		int[] roleIds = new int[userRoles.size()];
		roleIds = new int[userRoles.size()];
		for (int i=0; i<userRoles.size(); i++) {
			roleIds[i] = userRoles.get(i).getRoleId();
		}
		
		model.addAttribute("user", user);
		model.addAttribute("roles", roles);
		model.addAttribute("roleIds", roleIds);
		return "user/user_edit";
	}
	
	@RequiresPermissions("user:save")
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public String save(@ModelAttribute("preloadUser") User user,
			@RequestParam(value = "roleIds", required = false) int[] roleIds) {
//		if(StringUtils.isBlank(user.getUsername()))
//			errorMap.put("username", "用户名不能为空！");
//		if(StringUtils.isBlank(user.getPassword()))
//			errorMap.put("password", "请输入密码！");
//		if(!StringUtils.equals(user.getPassword(), user.getRepeatPassword())) {
//			errorMap.put("repeatPassword", "两次输入的密码不一致！");
//		}
//		if(StringUtils.isBlank(user.getName()))
//			errorMap.put("name", "请输入昵称！");
//		
//		if(!errorMap.isEmpty()) return INPUT;
//		校验是否重复、、、、、、、
		
	    // Hash加密存储
		String pwd = user.getPassword() != null ? user.getPassword().trim() : StringUtils.EMPTY;
        user.setPassword(shiroDbRealm.encrytPassword(pwd));
        user.setAvatar(StringUtils.EMPTY);
        user.setUid(StringUtils.EMPTY);

		if (user.getId() == 0) {// 新增
			try {
				userService.insert(user);
			} catch (ServiceException e) {
				logger.error("新增用户失败：{}",e.toString());
			}
		} else {// 修改
			try {
				userService.update(user);
			} catch (ServiceException e) {
				logger.error("修改用户失败：{}",e.toString());
			}
		}
		
		// 处理用户拥有的角色（映射表），先删后加
		int id = user.getId();
		try {
			userRoleService.deleteByUserId(id);
		} catch (ServiceException e) {
			logger.error("删除用户的角色失败：{}",e.toString());
		}
		if (ArrayUtils.isNotEmpty(roleIds)) {
			for (int roleId : roleIds) {
				UserRole userRole = new UserRole();
				userRole.setUserId(id);
				userRole.setRoleId(roleId);
				try {
					userRoleService.insert(userRole);
				} catch (ServiceException e) {
					logger.error("新增用户角色失败：{}",e.toString());
				}
			}
		}
		return "redirect:/user/user";
	}
	
	@RequiresPermissions("user:delete")
	@RequestMapping(value = "delete")
	public String delete(@RequestParam("ids") String ids) {
		try {
			userService.deleteByIds(ids);
		} catch (ServiceException e) {
			logger.error("删除用户失败：{}",e.toString());
		}
		return "redirect:/user/user";
	}
	
	@RequestMapping(value = StringUtils.EMPTY)
	public String list(
			@RequestParam(value = "cName", defaultValue = StringUtils.EMPTY) String cName,
			@RequestParam(value = "page", defaultValue = "1") int current,
			Model model) {
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put("cName", cName);
		Page page = new Page();
		page.setConditions(conditions);
		page.setCurrent(current);
		try {
			userService.getByPage(page);
		} catch (ServiceException e) {
			logger.error("查询用户信息失败：{}",e.toString());
		}
		model.addAttribute("page", page);

		return "user/user_list";
	}
	
	public List<Role> getRoles() {
		try {
			return roleService.getAll();
		} catch (ServiceException e) {
			logger.error("查询所有的角色失败：{}",e.toString());
		}
		return null;
	}

	@ModelAttribute("preloadUser")
	public User getUser(
			@RequestParam(value = "id", required = false) Integer id) {
		if (id != null && id != 0) {
			try {
				return userService.getById(id);
			} catch (ServiceException e) {
				logger.error("查询单个用户信息失败：{}",e.toString());
			}
		}
		return new User();
	}
	
}
